package concurrent;

import java.util.concurrent.TimeUnit;

class InterruptedSleepingThread extends Thread {

        @Override
        public void run() {
            doAPseudoHeavyWeightJob();
        }

        private void doAPseudoHeavyWeightJob() {
            for (int i=0;i<Integer.MAX_VALUE;i++) {
                //You are kidding me
                System.out.println(i + " " + i*2);
                //Let me sleep <evil grin> - 邪恶的微笑 哈哈 作者好逗
                boolean interrupted = Thread.currentThread().isInterrupted();
                if(interrupted) {
                    System.out.println("Thread interrupted\n Exiting...");
                    break;
                }else {
                    babySleep();
                }
            }
        }

        private void babySleep() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // 以下为我添加的代码，用来确认抛出InterruptException后会清除中断状态
                System.out.println("babySleep Thread.currentThread().isInterrupted(): " + Thread.currentThread().isInterrupted());
                // 以上为我添加的代码，用来确认抛出InterruptException后会清除中断状态
                Thread.currentThread().interrupt();
                // 以下为我添加的代码，用来查看Thread.interrupted()和Thread.currentThread().isInterrupted()的区别
                System.out.println("babySleep Thread.currentThread().isInterrupted(): " + Thread.currentThread().isInterrupted());
                System.out.println("babySleep: " + Thread.interrupted());
                System.out.println("babySleep: " + Thread.interrupted());
                System.out.println("babySleep Thread.currentThread().isInterrupted(): " + Thread.currentThread().isInterrupted());
                // 以上为我添加的代码，用来查看Thread.interrupted()和Thread.currentThread().isInterrupted()的区别
            }
        }
    }

   public class InterruptedSleepingThreadMain {

       public static void main(String[] args) throws InterruptedException {
           InterruptedSleepingThread thread = new InterruptedSleepingThread();
           thread.start();
           //Giving 10 seconds to finish the job.
           TimeUnit.SECONDS.sleep(5);
           //Let me interrupt
           thread.interrupt();
       }

    }